"""
题库管理模块 - 数据模型
"""
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
import uuid

User = get_user_model()


class Question(models.Model):
    """
    题目模型
    支持多种题型的智能题目系统
    """
    class QuestionType(models.TextChoices):
        CHOICE = 'choice', '单选题'
        MULTIPLE_CHOICE = 'multiple_choice', '多选题'
        FILL_BLANK = 'fill_blank', '填空题'
        SHORT_ANSWER = 'short_answer', '简答题'
        TRUE_FALSE = 'true_false', '判断题'
        ESSAY = 'essay', '论述题'
        CALCULATION = 'calculation', '计算题'

    class Difficulty(models.IntegerChoices):
        VERY_EASY = 1, '非常简单'
        EASY = 2, '简单'
        MEDIUM = 3, '中等'
        HARD = 4, '困难'
        VERY_HARD = 5, '非常困难'

    class Status(models.TextChoices):
        DRAFT = 'draft', '草稿'
        ACTIVE = 'active', '激活'
        INACTIVE = 'inactive', '未激活'
        ARCHIVED = 'archived', '已归档'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    type = models.CharField(
        max_length=20,
        choices=QuestionType.choices,
        default=QuestionType.CHOICE,
        verbose_name='题型'
    )
    title = models.CharField(max_length=200, verbose_name='题目标题')
    stem = models.TextField(verbose_name='题干')
    options = models.JSONField(
        default=list,
        blank=True,
        help_text='选项数据'
    )
    answer = models.TextField(verbose_name='标准答案')
    analysis = models.TextField(blank=True, verbose_name='解析')
    explanation = models.TextField(blank=True, verbose_name='解释说明')

    # 难度属性
    difficulty = models.IntegerField(
        choices=Difficulty.choices,
        default=Difficulty.MEDIUM,
        verbose_name='难度'
    )
    points = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        default=1.0,
        verbose_name='分值'
    )
    time_limit = models.IntegerField(
        null=True,
        blank=True,
        help_text='时间限制（秒）'
    )

    # 学科分类
    subject = models.CharField(max_length=100, verbose_name='科目')
    chapter = models.CharField(max_length=100, verbose_name='章节')
    section = models.CharField(max_length=100, blank=True, verbose_name='小节')
    tags = models.JSONField(default=list, blank=True, verbose_name='标签')
    keywords = models.JSONField(default=list, blank=True, verbose_name='关键词')

    # 创建者信息
    creator = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='created_questions',
        verbose_name='创建者'
    )
    is_ai_generated = models.BooleanField(default=False, verbose_name='AI生成')
    ai_generation_config = models.JSONField(
        default=dict,
        blank=True,
        verbose_name='AI生成配置'
    )
    usage_count = models.IntegerField(default=0, verbose_name='使用次数')
    correct_rate = models.DecimalField(
        max_digits=5,
        decimal_places=4,
        null=True,
        blank=True,
        verbose_name='正确率'
    )

    # 状态控制
    status = models.CharField(
        max_length=20,
        choices=Status.choices,
        default=Status.DRAFT,
        verbose_name='状态'
    )
    is_public = models.BooleanField(default=False, verbose_name='公开题目')

    # 审核信息
    reviewer = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='reviewed_questions',
        verbose_name='审核人'
    )
    review_status = models.CharField(
        max_length=20,
        choices=[
            ('pending', '待审核'),
            ('approved', '已通过'),
            ('rejected', '已拒绝')
        ],
        default='pending',
        verbose_name='审核状态'
    )
    review_comment = models.TextField(blank=True, verbose_name='审核意见')
    reviewed_at = models.DateTimeField(null=True, blank=True, verbose_name='审核时间')

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'questions'
        verbose_name = '题目'
        verbose_name_plural = '题目'
        indexes = [
            models.Index(fields=['type', 'difficulty']),
            models.Index(fields=['creator', 'created_at']),
            models.Index(fields=['subject', 'chapter']),
            models.Index(fields=['status']),
            models.Index(fields=['is_public']),
            models.Index(fields=['review_status']),
            models.Index(fields=['tags']),
        ]

    def __str__(self):
        return f"[{self.get_type_display()}] {self.title[:50]}"

    def get_formatted_options(self):
        """获取格式化选项"""
        if not self.options or self.type not in [
            self.QuestionType.CHOICE,
            self.QuestionType.MULTIPLE_CHOICE,
            self.QuestionType.TRUE_FALSE
        ]:
            return None

        options = {}
        option_labels = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']

        for i, option in enumerate(self.options):
            if i < len(option_labels):
                options[option_labels[i]] = option

        return options

    def update_usage_statistics(self, is_correct=None):
        """更新使用统计"""
        self.usage_count += 1

        if is_correct is not None:
            if self.correct_rate is None:
                self.correct_rate = 1.0 if is_correct else 0.0
            else:
                # 计算累计正确率
                total_attempts = self.usage_count
                correct_attempts = self.correct_rate * (total_attempts - 1) + (1 if is_correct else 0)
                self.correct_rate = correct_attempts / total_attempts

    def can_access(self, user):
        """检查用户是否可以访问题目"""
        if self.creator == user or self.is_public or user.is_admin_user:
            return True
        return False


class QuestionBank(models.Model):
    """
    题库模型
    用于组织和管理题目集合
    """
    class Type(models.TextChoices):
        PERSONAL = 'personal', '个人题库'
        SCHOOL = 'school', '学校题库'
        DEPARTMENT = 'department', '部门题库'
        SUBJECT = 'subject', '学科题库'
        EXAM = 'exam', '考试题库'

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100, verbose_name='题库名称')
    description = models.TextField(blank=True, verbose_name='题库描述')
    type = models.CharField(
        max_length=20,
        choices=Type.choices,
        default=Type.PERSONAL,
        verbose_name='题库类型'
    )

    # 学科信息
    subject = models.CharField(max_length=100, verbose_name='科目')
    grade_level = models.CharField(max_length=50, verbose_name='年级层次')
    difficulty_range = models.JSONField(
        default=list,
        help_text='难度范围 [min, max]'
    )

    # 统计信息
    question_count = models.IntegerField(default=0, verbose_name='题目数量')
    total_points = models.DecimalField(
        max_digits=8,
        decimal_places=2,
        default=0,
        verbose_name='总分值'
    )

    # 用户权限
    owner = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='owned_question_banks',
        verbose_name='所有者'
    )
    is_public = models.BooleanField(default=False, verbose_name='公开题库')
    allow_export = models.BooleanField(default=True, verbose_name='允许导出')

    # 版本信息
    version = models.CharField(max_length=20, default='1.0.0', verbose_name='版本')
    last_import_at = models.DateTimeField(null=True, blank=True, verbose_name='最后导入时间')

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'question_banks'
        verbose_name = '题库'
        verbose_name_plural = '题库'
        indexes = [
            models.Index(fields=['owner', 'type']),
            models.Index(fields=['subject', 'grade_level']),
            models.Index(fields=['is_public']),
            models.Index(fields=['type']),
        ]

    def __str__(self):
        return f"{self.name} ({self.get_type_display()})"

    def update_statistics(self):
        """更新统计信息"""
        questions = self.questions.all()
        self.question_count = questions.count()
        self.total_points = questions.aggregate(
            total=models.Sum('points')
        )['total'] or 0
        self.save(update_fields=['question_count', 'total_points'])

    def can_access(self, user):
        """检查用户是否可以访问题库"""
        if self.owner == user or self.is_public or user.is_admin_user:
            return True
        return False


class QuestionBankItem(models.Model):
    """
    题库题目项
    题库和题目的关联关系
    """
    class Status(models.TextChoices):
        ACTIVE = 'active', '激活'
        INACTIVE = 'inactive', '未激活'
        DEPRECATED = 'deprecated', '已废弃'

    question_bank = models.ForeignKey(
        QuestionBank,
        on_delete=models.CASCADE,
        related_name='question_items',
        verbose_name='题库'
    )
    question = models.ForeignKey(
        Question,
        on_delete=models.CASCADE,
        related_name='bank_items',
        verbose_name='题目'
    )
    custom_points = models.DecimalField(
        max_digits=5,
        decimal_places=2,
        null=True,
        blank=True,
        help_text='自定义分值'
    )
    custom_difficulty = models.IntegerField(
        null=True,
        blank=True,
        help_text='自定义难度'
    )
    status = models.CharField(
        max_length=20,
        choices=Status.choices,
        default=Status.ACTIVE,
        verbose_name='状态'
    )
    order = models.IntegerField(default=0, verbose_name='排序')

    added_at = models.DateTimeField(auto_now_add=True, verbose_name='添加时间')
    added_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name='添加者'
    )

    class Meta:
        db_table = 'question_bank_items'
        verbose_name = '题库题目'
        verbose_name_plural = '题库题目'
        unique_together = ['question_bank', 'question']
        indexes = [
            models.Index(fields=['question_bank', 'status']),
            models.Index(fields=['question', 'status']),
            models.Index(fields=['order']),
        ]

    def __str__(self):
        return f"{self.question_bank.name} - {self.question.title}"

    @property
    def effective_points(self):
        """获取有效分值"""
        return self.custom_points or self.question.points

    @property
    def effective_difficulty(self):
        """获取有效难度"""
        return self.custom_difficulty or self.question.difficulty


class QuestionTag(models.Model):
    """
    题目标签
    用于分类和检索题目
    """
    name = models.CharField(max_length=50, unique=True, verbose_name='标签名称')
    description = models.TextField(blank=True, verbose_name='标签描述')
    color = models.CharField(max_length=7, default='#1890ff', verbose_name='标签颜色')
    category = models.CharField(max_length=50, default='general', verbose_name='标签类别')

    usage_count = models.IntegerField(default=0, verbose_name='使用次数')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'question_tags'
        verbose_name = '题目标签'
        verbose_name_plural = '题目标签'
        indexes = [
            models.Index(fields=['category']),
            models.Index(fields=['usage_count']),
        ]

    def __str__(self):
        return self.name


class QuestionTagRelation(models.Model):
    """
    题目标签关系
    建立题目和标签的多对多关系
    """
    question = models.ForeignKey(
        Question,
        on_delete=models.CASCADE,
        related_name='tag_relations',
        verbose_name='题目'
    )
    tag = models.ForeignKey(
        QuestionTag,
        on_delete=models.CASCADE,
        related_name='question_relations',
        verbose_name='标签'
    )

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    created_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name='创建者'
    )

    class Meta:
        db_table = 'question_tag_relations'
        verbose_name = '题目标签关系'
        verbose_name_plural = '题目标签关系'
        unique_together = ['question', 'tag']
        indexes = [
            models.Index(fields=['question']),
            models.Index(fields=['tag']),
        ]

    def __str__(self):
        return f"{self.question.title[:30]} - {self.tag.name}"


class QuestionUsageHistory(models.Model):
    """
    题目使用历史
    记录题目的使用情况
    """
    class UsageType(models.TextChoices):
        EXAM = 'exam', '考试'
        PRACTICE = 'practice', '练习'
        PREVIEW = 'preview', '预览'
        IMPORT = 'import', '导入'
        EXPORT = 'export', '导出'

    question = models.ForeignKey(
        Question,
        on_delete=models.CASCADE,
        related_name='usage_history',
        verbose_name='题目'
    )
    user = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name='用户'
    )
    usage_type = models.CharField(
        max_length=20,
        choices=UsageType.choices,
        verbose_name='使用类型'
    )
    context = models.JSONField(
        default=dict,
        blank=True,
        verbose_name='使用上下文'
    )
    is_correct = models.BooleanField(
        null=True,
        blank=True,
        verbose_name='是否正确'
    )
    time_spent = models.IntegerField(
        null=True,
        blank=True,
        help_text='用时（秒）'
    )

    created_at = models.DateTimeField(auto_now_add=True, verbose_name='使用时间')
    ip_address = models.GenericIPAddressField(null=True, blank=True, verbose_name='IP地址')

    class Meta:
        db_table = 'question_usage_history'
        verbose_name = '题目使用历史'
        verbose_name_plural = '题目使用历史'
        indexes = [
            models.Index(fields=['question', 'created_at']),
            models.Index(fields=['user', 'usage_type']),
            models.Index(fields=['usage_type', 'created_at']),
        ]

    def __str__(self):
        return f"{self.question.title[:30]} - {self.get_usage_type_display()}"